package com.adcc.ags.cgw.service;

import com.adcc.ags.cgw.configuration.UserListFactory;
import com.adcc.ags.cgw.entity.msg.MsgSendResult;
import com.adcc.ags.cgw.entity.msg.MsgSendState;
import com.adcc.ags.cgw.entity.user.User;
import com.adcc.ags.cgw.managed.downlink.DownlinkForward;
import com.adcc.ags.cgw.entity.msg.CGWMsg;
import com.adcc.ags.cgw.entity.msg.MsgType;
import com.adcc.ags.cgw.managed.uplink.UplinkForward;
import com.adcc.ags.cgw.utils.Constant;
import com.adcc.utility.log.Log;
import com.google.common.base.Strings;

import java.util.Iterator;

/**
 * 消息发送服务
 */
public class MsgSenderServiceImpl extends MsgSenderService {

    /**
     * 查找用户ID
     * @param dest
     * @return
     */
    private String findUserID(String dest){
        String strUsers = Strings.nullToEmpty("");
        for(User user : UserListFactory.getInstance().getUserList()){
            if(dest.equals(user.getRecvQueue())){
                strUsers =  user.getId();
                break;
            }
        }
        return strUsers;
    }

    @Override
    protected MsgSendResult sendUplinkMsg(CGWMsg msg) {
        MsgSendResult result = new MsgSendResult();
        try{
            DownlinkForward.getInstance().sendMsgToAMQS(msg.getContent().getContent());
            Log.info(MsgSenderService.class.getName(), "send uplink message from user:" + msg.getSender() + ", message:\r\n" + msg.getContent().toString());
            result.setState(MsgSendState.Success);
        }catch (Exception ex){
            Log.error(MsgSenderService.class.getName(), "send uplink message from user:" + msg.getSender()+ " failed, message:\r\n" + msg.getContent().toString(),ex);
            result.setState(MsgSendState.Fail);
            result.setUnReceiver("1");
        }
        return result;
    }

    @Override
    protected MsgSendResult sendDownlinkMsg(CGWMsg msg) {
        boolean flag = false;
        String strUnReceiver = Strings.nullToEmpty("");
        MsgSendResult result = new MsgSendResult();
        if(msg.getDestination() != null && msg.getDestination().size() > 0){
            for (Iterator<String> iterator = msg.getDestination().iterator();iterator.hasNext();) {
                String qName = iterator.next();
                try {
                    UplinkForward.getInstance().sendMsgToBGS(qName,msg.getContent().getContent(),msg.getType(),msg.getSender());
                    if(msg.getType() == MsgType.Downlink){
                        Log.info(MsgSenderService.class.getName(), "send downlink message to queue:" + qName + ", message:\r\n" + msg.getContent().toString());
                    }else{
                        Log.info(MsgSenderService.class.getName(), "send ground message to queue:" + qName + ". message：\r\n" + msg.getContent().toString());
                    }
                    flag = true;
                } catch (Exception ex) {
                    if(msg.getType() == MsgType.Downlink){
                        Log.error(MsgSenderService.class.getName(), "send downlink message to queue:" + qName + " failed, message:\r\n" + msg.getContent().toString(),ex);
                    }else{
                        Log.error(MsgSenderService.class.getName(), "send ground message to queue:" + qName + " failed, message:\r\n" + msg.getContent().toString(),ex);
                    }
                    String strUserID = findUserID(qName);
                    if(!Strings.isNullOrEmpty(strUserID)) {
                        strUnReceiver += strUserID + ",";
                    }
                }
            }
            if (strUnReceiver.endsWith(",")) {
                strUnReceiver = strUnReceiver.substring(0, strUnReceiver.length() - 1);
            }
            if(flag){
                if(Strings.isNullOrEmpty(strUnReceiver)){
                    result.setState(MsgSendState.Success);
                }else {
                    result.setState(MsgSendState.Warning);
                    result.setUnReceiver(strUnReceiver);
                }
            }else{
                result.setState(MsgSendState.Fail);
                result.setUnReceiver(strUnReceiver);
            }
        }
        return result;
    }

    @Override
    public void onReceive(Object message) {
        super.onReceive(message);
        try{
            if(message instanceof CGWMsg){
                CGWMsg msg = (CGWMsg)message;
                if(msg.getType() == MsgType.Uplink){
                    if(msg.getDestination().size() > 0){
                        MsgSendResult result1 = sendUplinkMsg(msg);
                        MsgSendResult result2 = sendDownlinkMsg(msg);
                        if(result1.getState() == MsgSendState.Fail){
                            saveMsg(msg,"F",result1.getUnReceiver(), Constant.STRING_ERROR_CODE_SENDFAILED);
                        }else {
                            if(result2.getState() == MsgSendState.Success){
                                saveMsg(msg,"S");
                            }else{
                                saveMsg(msg,"W",result2.getUnReceiver(),"");
                            }
                        }
                    }else {
                        MsgSendResult result = sendUplinkMsg(msg);
                        if(result.getState() == MsgSendState.Success){
                            saveMsg(msg,"S");
                        }else{
                            saveMsg(msg,"F",result.getUnReceiver(), Constant.STRING_ERROR_CODE_SENDFAILED);
                        }
                    }
                }else {
                    MsgSendResult result = sendDownlinkMsg(msg);

                    // 保存消息
                    if(result.getState() == MsgSendState.Success){
                        saveMsg(msg,"S");
                    }else if(result.getState() == MsgSendState.Warning){
                        saveMsg(msg,"W",result.getUnReceiver(),"");
                    }else{
                        saveMsg(msg,"F",result.getUnReceiver(),Constant.STRING_ERROR_CODE_SENDFAILED);
                    }
                }
            }else{
                unhandled(message);
            }
        }catch (Exception ex){
            Log.error(MsgSenderService.class.getName(),"onReceive() error",ex);
        }
    }
}
